var app = getApp();
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

module.exports = {
  formatTime: formatTime
}

function getheader() {
  var header = {
    'content-type': 'application/x-www-form-urlencoded',
    'version': '1.0',
  };
  return header;
};
// 客服：
function getheaderCli() {
  var headerCli = {
    'content-type': 'text/xml',
    'version': '1.0',
  };
  return headerCli;
};

function postUrlCli(url, data, callback) {
  data.api_key = 'c1dca569396ba260fe6a7d552b6b7d74';
  data.user_token = wx.getStorageSync('token');
  url = getApp().clientUrl + url;
  console.log("请求的接口: " + url, data);
  wx.request({
    url: url,
    method: "POST",
    data: data,
    header: getheaderCli(),
    success: function (res) {
      console.log("返回的结果: " + url, res.data);
      callback(res);
    },
    fail: function (res) {
      console.log(res);
      callback(null);
    }
  })
}



function postUrl(url, data, callback) {
  data.api_key = 'c1dca569396ba260fe6a7d552b6b7d74';
  data.user_token = wx.getStorageSync('token');
  url = getApp().clientUrl + url;
  console.log("请求的接口: " + url, data);
  wx.request({
    url: url,
    method: "POST",
    data: data,
    header: getheader(),
    success: function (res) {
      console.log("返回的结果: " + url, res.data);
      callback(res);
    },
    fail: function (res) {
      console.log(res);
      callback(null);
    }
  })
}

function getUrl(url, callback) {
  wx.request({
    url: url,
    method: "GET",
    header: getheader(),
    success: function (res) {
      console.log(url);
      console.log(res);
      if (res.data.code == 200) {
        callback(res);
      } else {
        console.log("error");
      }
    },
    fail: function (res) {
      callback(null);
    }
  })
}
// 生成指定长度的字符串
function randomStr(a) {
  var d,
    e,
    b = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
    c = "";
  for (d = 0; a > d; d += 1)
    e = Math.random() * b.length, e = Math.floor(e), c += b.charAt(e);
  return c
}



module.exports = {
  getUrl: getUrl,
  postUrl: postUrl,
  randomStr: randomStr,
  postUrlCli: postUrlCli
}